package online.westonline.com.westonline.ui;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.easy.west.westclient.Constants;
import com.google.gson.Gson;
import com.grandbroad.online.greendao.NodeBeanDao;
import com.tangxiaolv.telegramgallery.GalleryActivity;
import com.tangxiaolv.telegramgallery.GalleryConfig;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.adapter.MyPerviewAdpter;
import online.westonline.com.westonline.adapter.PopWindowTypeAdpter;
import online.westonline.com.westonline.base.BaseActivity;
import online.westonline.com.westonline.entry.IamgeBean;
import online.westonline.com.westonline.entry.NodeBean;
import online.westonline.com.westonline.utils.DensityUtils;
import online.westonline.com.westonline.utils.GreenDaoUtils;
import online.westonline.com.westonline.utils.TimeUtil;
import online.westonline.com.westonline.utils.ToastUtils;
import online.westonline.com.westonline.utils.UiUtlis;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 工作笔记添加
 *
 */
public class EditNodeActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {


    @BindView(R.id.tv_topbar_title)
    TextView tvTopbarTitle;
    @BindView(R.id.tv_topbar_title_center)
    TextView tvTopbarTitleCenter;
    @BindView(R.id.tv_topbar_menu)
    TextView tvTopbarMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.edit_content)
    EditText editContent;
    @BindView(R.id.img_imgbg)
    ImageView imgImgbg;
    @BindView(R.id.tv_selcet_img)
    TextView tvSelcetImg;
    @BindView(R.id.img_addimg)
    ImageView imgAddimg;
    @BindView(R.id.btn_save_ndoe)
    Button btnSaveNdoe;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.card_type_select)
    CardView cardTypeSelect;
    @BindView(R.id.recycler_previewshow)
    RecyclerView recyclerPreviewshow;
    @BindView(R.id.edit_title)
    EditText editTitle;
    private RecyclerView recycler_type;
    List<String> type = new ArrayList<>();
    private PopWindowTypeAdpter popWindowTypeAdpter;
    private boolean isselcet = false;
    private List<String> photos = new ArrayList<>();
    private String img_data;
    private MyPerviewAdpter perviewAdpter;
    private NodeBeanDao beanDao;

    @Override
    protected void initview() {
        toolbar.setBackgroundColor(UiUtlis.getColor(R.color.colorAppTheme));
        toolbar.setTitleTextColor(UiUtlis.getColor(R.color.colorMenuBtn));
        toolbar.setTitle("添加笔记");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_keyboard_arrow_left_blue_500_24dp);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        initrecyclerview();
        configtype();
        initsession();
    }

    private void initrecyclerview() {
        perviewAdpter = new MyPerviewAdpter();
        recyclerPreviewshow.setLayoutManager(new GridLayoutManager(this,3,GridLayoutManager.VERTICAL,false));
        recyclerPreviewshow.setAdapter(perviewAdpter);
        recyclerPreviewshow.setNestedScrollingEnabled(false);
        //RecyclerViewUtils.init(this,recyclerPreviewshow,perviewAdpter);
        perviewAdpter.setClicktodelte(new MyPerviewAdpter.clicktodelte() {
            @Override
            public void delete(int pos, String path) {
                photos.remove(path);
                perviewAdpter.setPaths(photos);
                perviewAdpter.notifyItemRemoved(pos);
                //3次(在集合改变时做出对应变化)
                IamgeBean bean = new IamgeBean();
                bean.setPaths(photos);
                Gson gson = new Gson();
                img_data = gson.toJson(bean);
            }
        });
        perviewAdpter.setClicktoadd(new MyPerviewAdpter.clicktoadd() {
            @Override
            public void delete() {
                askPermission();
            }
        });
    }

    /**
     * 初始化type
     */
    private void configtype() {
        //获取屏幕初始亮度
        final int brights = getScreenBrightness(EditNodeActivity.this);
        ViewGroup.LayoutParams lp = cardTypeSelect.getLayoutParams();
        popWindowTypeAdpter = new PopWindowTypeAdpter();
        type.add(Constants.TYPE_NODE);
        type.add(Constants.TYPE_FORGIVING);
        type.add(Constants.TYPE_REMENBER);
        type.add(Constants.TYPE_WORDS);
        type.add(Constants.TYPE_ABOUTWORKS);
        popWindowTypeAdpter.setArrays(type);
        View view = LayoutInflater.from(EditNodeActivity.this).inflate(R.layout.popwindow_type_select, null);
        recycler_type = view.findViewById(R.id.recycler_pop_nodetype);
        recycler_type.setLayoutManager(new LinearLayoutManager(this));
        recycler_type.setAdapter(popWindowTypeAdpter);
        popWindowTypeAdpter.notifyDataSetChanged();
        final PopupWindow window = new PopupWindow(view, lp.width - DensityUtils.px2dip(getApplicationContext(), 5), lp.height);
        window.setFocusable(true);
        window.setOutsideTouchable(true);
        //配置点击事件
        cardTypeSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setBrightness(EditNodeActivity.this, 0.5f);
                window.showAsDropDown(v);
            }
        });
        //window关闭
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBrightness(EditNodeActivity.this, 1f);
            }
        });
        //adpter点击
        popWindowTypeAdpter.setClick(new PopWindowTypeAdpter.itemClick() {
            @Override
            public void click(int pos, String type) {
                if (window.isShowing()) {
                    tvType.setText(type);
                    isselcet = true;
                    window.dismiss();
                }

            }
        });

    }

    private void initsession() {
        //保存按钮
        btnSaveNdoe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String content = editContent.getText().toString();
                final String title = editTitle.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    ToastUtils.showToast("笔记一定要认真输入哦！");
                    return;
                }
                //选择了主题
                if (isselcet) {
                    String type = tvType.getText().toString();
                    NodeBean nodeBean = new NodeBean();
                    nodeBean.setType(type);
                    nodeBean.setContent(content);
                    nodeBean.setTime(TimeUtil.getLocalTime(System.currentTimeMillis()));
                    if (!TextUtils.isEmpty(title))
                    {
                        nodeBean.setTitle(title);
                    }
                    if (!TextUtils.isEmpty(img_data)) {
                        //选择了图片
                        nodeBean.setImg_paths(img_data);
                    }
                    beanDao.insert(nodeBean);
                    finish();
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(EditNodeActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("您并未选择笔记类型,点击确定后\n以后将在没有选择类型的情况下默认将笔记存在便签里");
                    builder.setNegativeButton("取消", null);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String type = Constants.TYPE_NODE;
                            NodeBean nodeBean = new NodeBean();
                            nodeBean.setType(type);
                            nodeBean.setContent(content);
                            nodeBean.setTime(TimeUtil.getLocalTime(System.currentTimeMillis()));
                            if (!TextUtils.isEmpty(img_data)) {
                                //选择了图片
                                nodeBean.setImg_paths(img_data);
                            }
                            if (!TextUtils.isEmpty(title))
                            {
                                nodeBean.setTitle(title);
                            }
                            beanDao.insert(nodeBean);
                            finish();
                        }
                    });
                    builder.show();
                }

            }
        });
        //打开相册
        imgAddimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                askPermission();
            }
        });
    }

    /**
     * 问权限
     */
    private void askPermission() {
        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, permissions)) {
            //打开相册
            openGrally();
        } else {
            EasyPermissions.requestPermissions(this, "申请读取相册权限", 10, permissions);
        }
    }

    @Override
    protected void initdata() {
        beanDao = GreenDaoUtils.getInstance().getDaoSession().getNodeBeanDao();
    }

    @Override
    protected int setlayout() {
        return R.layout.activity_add_node;
    }

    /**
     * 设置亮度
     *
     * @param activity
     * @param brightness
     */
    public static void setBrightness(Activity activity, float brightness) {
        // Settings.System.putInt(activity.getContentResolver(),
        // Settings.System.SCREEN_BRIGHTNESS_MODE,
        // Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = brightness;
        activity.getWindow().setAttributes(lp);
    }


    /**
     * 获取屏幕的亮度
     *
     * @param activity
     * @return
     */
    public static int getScreenBrightness(Activity activity) {
        int nowBrightnessValue = 0;
        ContentResolver resolver = activity.getContentResolver();
        try {
            nowBrightnessValue = Settings.System.getInt(
                    resolver, Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nowBrightnessValue;
    }

    /**
     * 预览图展示
     * 改用recyclerview
     */
    private void showperiview() {
        if (photos.size()>9)
        {
            //超出最大选择数
            ToastUtils.showToast("最多只能选择9张");
            //移除9以后的
            for (int i=0;i<photos.size();i++)
            {
                if (i>8)
                {
                    photos.remove(i);
                }
            }
            return;
        }
        //2次
        IamgeBean bean = new IamgeBean();
        bean.setPaths(photos);
        Gson gson = new Gson();
        img_data = gson.toJson(bean);
        perviewAdpter.setPaths(photos);
        perviewAdpter.notifyDataSetChanged();
    }

    /**
     * 重新获取焦点
     */
    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        openGrally();
    }

    /**
     * 打开相册
     */
    private void openGrally() {
        GalleryConfig config = new GalleryConfig.Build()
                .singlePhoto(false)
                //最多9张
                .limitPickPhoto(9)
                .hintOfPick("最多只能选择9张图片")
                .filterMimeTypes(new String[]{"image/jpeg/png"})
                .build();
        GalleryActivity.openActivity(EditNodeActivity.this, 15, config);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取选中的照片路径
        if (data == null) {
            //点了取消
            return;
        }
        if (photos.size() > 0) {
            photos.addAll((List<String>) data.getSerializableExtra(GalleryActivity.PHOTOS));
        } else {
            photos = (List<String>) data.getSerializableExtra(GalleryActivity.PHOTOS);
        }
        //预览图展示
        showperiview();
        if (photos.size() > 0&&photos.size()<10) {
            //转换成json文本
            //数据库不支持集合
            //1次
            IamgeBean bean = new IamgeBean();
            bean.setPaths(photos);
            Gson gson = new Gson();
            img_data = gson.toJson(bean);
        }
    }


    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        ToastUtils.showToast("抱歉,没有权限");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }



}
